package com.student.teacher.service.impl;

import com.student.common.entity.Teacher;
import com.student.teacher.service.TeacherService;
import com.student.teacher.repository.TeacherRepository;
import com.student.teacher.feign.UserServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;

/**
 * 教师服务实现类
 * 
 * @author student
 * @date 2025
 */
@Service
public class TeacherServiceImpl implements TeacherService {
    
    @Autowired
    private TeacherRepository teacherRepository;
    
    @Autowired
    private UserServiceClient userServiceClient;
    
    @Override
    public Page<Teacher> getTeacherList(Pageable pageable, String name, String title, String department, String employeeId, String status) {
        if (StringUtils.hasText(name) || StringUtils.hasText(title) || StringUtils.hasText(department) || 
            StringUtils.hasText(employeeId) || StringUtils.hasText(status)) {
            return teacherRepository.findByConditions(name, title, department, employeeId, status, pageable);
        }
        return teacherRepository.findAll(pageable);
    }
    
    @Override
    public Teacher getTeacherById(String teacherId) {
        return teacherRepository.findById(teacherId).orElse(null);
    }
    
    @Override
    public boolean addTeacher(Teacher teacher) {
        if (teacherRepository.existsById(teacher.getTeacherId())) {
            return false;
        }
        
        teacher.setCreateTime(LocalDateTime.now());
        teacher.setUpdateTime(LocalDateTime.now());
        // 如果没有设置状态，默认为在职
        if (teacher.getStatus() == null || teacher.getStatus().isEmpty()) {
            teacher.setStatus("在职");
        }
        
        // 保存教师信息
        teacherRepository.save(teacher);
        
        // 同步创建用户账号
        try {
            boolean userCreated = userServiceClient.createUser(
                teacher.getTeacherId(),  // 用户名使用工号
                teacher.getName(),       // 真实姓名
                "教师",                 // 角色
                teacher.getTeacherId(), // 关联ID使用工号
                teacher.getEmail(),      // 邮箱
                teacher.getPhone()       // 电话
            );
            
            if (!userCreated) {
                System.err.println("教师用户账号创建失败: " + teacher.getTeacherId());
                // 注意：这里不返回false，因为教师信息已经保存成功
                // 只是用户账号创建失败，可以通过其他方式补救
            }
        } catch (Exception e) {
            System.err.println("调用用户服务创建教师账号失败: " + e.getMessage());
            // 同样不返回false，避免影响教师信息的保存
        }
        
        return true;
    }
    
    @Override
    public boolean updateTeacher(Teacher teacher) {
        if (!teacherRepository.existsById(teacher.getTeacherId())) {
            return false;
        }
        
        // 获取现有教师信息，保留创建时间
        Teacher existingTeacher = teacherRepository.findById(teacher.getTeacherId()).orElse(null);
        if (existingTeacher != null) {
            teacher.setCreateTime(existingTeacher.getCreateTime());
        }
        
        teacher.setUpdateTime(LocalDateTime.now());
        teacherRepository.save(teacher);
        
        // 同步更新用户信息
        try {
            boolean userUpdated = userServiceClient.updateUserInfo(
                teacher.getTeacherId(),  // 用户名使用工号
                teacher.getName(),      // 真实姓名
                teacher.getEmail(),     // 邮箱
                teacher.getPhone()      // 电话
            );
            
            if (!userUpdated) {
                System.err.println("教师用户信息更新失败: " + teacher.getTeacherId());
            }
        } catch (Exception e) {
            System.err.println("调用用户服务更新教师信息失败: " + e.getMessage());
        }
        
        return true;
    }
    
    @Override
    public boolean deleteTeacher(String teacherId) {
        if (!teacherRepository.existsById(teacherId)) {
            return false;
        }
        
        // 检查是否有授课记录
        // 这里可以调用成绩服务检查，简化处理直接删除
        teacherRepository.deleteById(teacherId);
        
        // 同步删除用户账号
        try {
            boolean userDeleted = userServiceClient.deleteUser(teacherId);
            if (!userDeleted) {
                System.err.println("教师用户账号删除失败: " + teacherId);
            }
        } catch (Exception e) {
            System.err.println("调用用户服务删除教师账号失败: " + e.getMessage());
        }
        
        return true;
    }
    
    @Override
    public long getTeacherCount() {
        return teacherRepository.count();
    }
}
